package com.rocksdata.mc.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.ctz.commonframe.ui.WebViewActivity;
import com.ctz.commonframe.utils.CommonUtil;
import com.ctz.commonframe.utils.Logger;
import com.ctz.commonframe.utils.SharedPrefrencesUtil;
import com.rocksdata.mc.MobileCampusApplication;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.business.CampusAppManager;
import com.rocksdata.mc.business.UserInfoManager;
import com.rocksdata.mc.business.location.UnreadManager;
import com.rocksdata.mc.ui.activity.MainActivity;
import com.rocksdata.mc.ui.activity.OATreatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by 陈堂正 on 2016/12/1.
 */
public class JPushMessageReceiver extends BroadcastReceiver{
    private static final String TAG = "JPushMessageReceiver";
    private static final String APPLICATION_ID = "com.rocksdata.mc.maoyixuexiao";
    /**
     * 客饭券业务
     */
    private static final int BUSINESS_TYPE_GUEST_MEAL = 1;

    /**
     * 客饭券申请中，待审核
     */
    private static final int GUEST_MEAL_STATUS_APPLING = 1;

    /**
     * 客饭券申请审核未通过
     */
    private static final int GUEST_MEAL_STATUS_UNPASS = 2;

    /**
     * 客饭券申请审核通过，未使用
     */
    private static final int GUEST_MEAL_STATUS_NOT_USED = 3;

    /**
     * 客饭券申请审核通过，已使用
     */
    private static final int GUEST_MEAL_STATUS_USED = 4;

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        String extraData = bundle.getString(JPushInterface.EXTRA_EXTRA);
        JSONObject json;
        String appType;
        JSONObject dataJson = null;
        String unreadCode = "";
//        Logger.e(TAG, "action:" + intent.getAction() + ", extras: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Logger.e(TAG, "收到RegistrationId : " + regId);
            //send the Registration Id to your server...

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Logger.e(TAG, "收到自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Logger.e(TAG, "收到通知，通知ID: " + notificationId);
            // 如果应用未启动，先初始话存储，用来保存未读消息
            if (!CommonUtil.isProcessAlive(context, APPLICATION_ID)) {
                SharedPrefrencesUtil.init(context);
            }


            // 保存未读消息
            if (!TextUtils.isEmpty(extraData)) {
                try {
                    json = new JSONObject(extraData);
                    appType = json.getString("type");
                    String data = json.getString("data");
                    if (!TextUtils.isEmpty(data))
                        dataJson = new JSONObject(data);

                    if ("app44".equals(appType)) {
                        String code = dataJson.getString("proposer_code");
                        unreadCode = code;
                    } else if("app12".equals(appType)){
                        String instanceId = dataJson.getString("instanceID");
                        String taskName = dataJson.getString("node");
                        unreadCode = instanceId + taskName;
                    } else if ("app51".equals(appType)) {
                        unreadCode = dataJson.getString("instanceID");
                    }
                    UnreadManager.setUnread(appType, unreadCode);
                } catch (JSONException e) {
                    Logger.e("parse json error");
                }
            }

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Logger.e(TAG, "用户点击打开了通知");
            Intent mainIntent;
            //判断app进程是否存活，跳转MainActivity之后，通过接受的数据类型分发到各子应用中
            if(CommonUtil.isProcessAlive(context, APPLICATION_ID)){
                Logger.e(TAG, "APP进程还在");
                mainIntent = new Intent(context, MainActivity.class);
                mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }else {
                Logger.e(TAG, "APP进程已被杀死");
                mainIntent = context.getPackageManager().getLaunchIntentForPackage(APPLICATION_ID);
                mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            }


            Intent businessIntent = null;
            String url = null;
            if (!TextUtils.isEmpty(extraData)) {
                Logger.e("extraData:" + extraData);
                try {
                    json = new JSONObject(extraData);
                    appType = json.getString("type");
                    String data = json.getString("data");
                    if (!TextUtils.isEmpty(data))
                        dataJson = new JSONObject(data);
                    if ("app44".equals(appType)) { //客饭券
                        int labour = dataJson.getInt("labour");
                        int table = dataJson.getInt("table");
                        String code = dataJson.getString("proposer_code");
                        url = CampusAppManager.getMealDetailUrl(labour, table, code);
                        Logger.e("客饭券详情页url：" + url);
                    } else if ("app12".equals(appType)) { //待办已办
                        String processName = dataJson.getString("process");
                        String instanceId = dataJson.getString("instanceID");
                        String taskName = dataJson.getString("node");
                        unreadCode = instanceId + taskName;
                        url = CampusAppManager.getOADetailUrl(processName, instanceId, taskName, false);
                        Logger.e("待办已办详情页url：" + url);
                    } else if ("app51".equals(appType)) { //我的申请
                        String processName = dataJson.getString("process");
                        String instanceId = dataJson.getString("instanceID");
                        String taskName = dataJson.getString("node");
                        unreadCode = instanceId;
                        url = CampusAppManager.getOADetailUrl(processName, instanceId, taskName, true);
                    }
                    UnreadManager.setRead(appType, unreadCode);
                } catch (JSONException e) {
                    Logger.e(TAG, "push message extra JSON error!");
                } catch (UnsupportedEncodingException e1) {
                    Logger.e(TAG, "webview url encoding error");
                }
            }

            if (url == null) {
                context.startActivity(mainIntent);
            } else {
                businessIntent = new Intent(context, WebViewActivity.class);
                businessIntent.putExtra(WebViewActivity.EXTRA_KEY_URL, url);
                context.startActivities(new Intent[]{mainIntent, businessIntent});
            }
        } else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Logger.e(TAG, "收到网络连接变化的通知，connected：" + connected);
        } else {
            Logger.e(TAG, "收到不明通知，action：" + intent.getAction());
        }
    }

    private static class ReceiverData {
        private int businessType;
        private String businessId;

        public int getBusinessType() {
            return businessType;
        }

        public void setBusinessType(int businessType) {
            this.businessType = businessType;
        }

        public String getBusinessId() {
            return businessId;
        }

        public void setBusinessId(String businessId) {
            this.businessId = businessId;
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            }else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    Logger.e(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it =  json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " +json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Logger.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }
}
